package wjx.database.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

import javax.swing.Box;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import wjx.database.bean.JTableUtils;
import wjx.database.bean.StringUtil;
import wjx.database.jdbc.JDBCUtils;

public class AddFrm extends JFrame {
	// implements TableModelListener
	private JPanel contentPane;
	private Box box1, box2, box;
	private JTextField tField, tType;
	private JLabel[] label;
	private JTable table, table_;
	private DefaultTableModel model,model_;
	private int num;
	private JButton button1, button2, button3;
	private String[] tableTitle = { "列名", "数据类型(长度)", "不为空", "是否加密" };
	private Class[] typeArray = { Object.class, Object.class, Boolean.class, Boolean.class };
	private String sql;
	private String tbName;
	private String alter;
	private String code="";
	private String[] qQuery;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AddFrm frame = new AddFrm("test");
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public AddFrm(String name) {
//		setResizable(false);
		List<String> queryList = JDBCUtils.GetTableCol(name);
		qQuery = new String[queryList.size()];
		queryList.toArray(qQuery);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		tbName = name;
		code = JDBCUtils.GetTableRemarks(name);

		List<String> tableNames = JDBCUtils.GetTableColAnd(name);
		setTitle("数据录入-表'" + name + "'");

		num = tableNames.size() / 2;
		String[] s = new String[tableNames.size()];
		tableNames.toArray(s);
		String[] head = new String[num];
		for (int i = 0; i < num; i++) {
			head[i] = s[2 * i] + "(" + s[2 * i + 1] + ")";
		}

		Box bHead = Box.createHorizontalBox();
		bHead.add(new JLabel("请输入想要插入的数据"));

		table = new JTable(1, num);
		model = (DefaultTableModel) table.getModel();
		model.setColumnIdentifiers(head);
		table.setModel(model);
//		model.addTableModelListener(table);
		JScrollPane scrollPane = new JScrollPane(table);

//		table.setPreferredScrollableViewportSize(new Dimension(450, 50));
		scrollPane.setPreferredSize(new Dimension(450, 50));
		JTableUtils.setTable(table);

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 100);
		setResizable(false);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		button1 = new JButton("取消");
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				quitActionperformed(e);
			}
		});

		button2 = new JButton("确定");
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				confirmerformed(e);
			}
		});

		box1 = Box.createHorizontalBox();
		box1.add(scrollPane);

		Box bMid1 = Box.createHorizontalBox();
		bMid1.add(new JLabel("为该表添加新的属性列"));

		table_ = new JTable();
		model_ = new DefaultTableModel(1, 4) {
			public Class getColumnClass(int columnIndex) {
				return typeArray[columnIndex];// 返回每一列的数据类型
			}
		};
		model_.setColumnIdentifiers(tableTitle);
		table_.setModel(model_);
		// 获得表格的表格列类
		TableColumn tc1 = table_.getColumnModel().getColumn(2);
		TableColumn tc2 = table_.getColumnModel().getColumn(3);
		tc1.setCellEditor(new DefaultCellEditor(new JCheckBox()));
		tc2.setCellEditor(new DefaultCellEditor(new JCheckBox()));
		// 设置网格线
		table_.setShowHorizontalLines(true);
		table_.setShowVerticalLines(true);
		table_.setBorder(new EtchedBorder(EtchedBorder.RAISED));
		table_.setGridColor(Color.BLACK);
		table_.setRowHeight(25);

		JScrollPane scroll1 = new JScrollPane(table_);
		scroll1.setPreferredSize(new Dimension(450, 50));

		Box bMid2 = Box.createHorizontalBox();
		button3 = new JButton("确认添加");
		button3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				confirmerformed1(e);
			}
		});
		bMid2.add(button3);

		box2 = Box.createHorizontalBox();
		box2.add(button1);
		box2.add(button2);
		box = Box.createVerticalBox();
		box.add(bHead);
		box.createVerticalStrut(10);
		box.add(box1);
		box.add(box2);
		box.add(bMid1);
		box.add(scroll1);
		box.add(bMid2);

		contentPane.add(box);
		pack();
		this.setLocationRelativeTo(null);
	}

	private void confirmerformed1(ActionEvent e) {
		// 实现alter添加新的属性列
		int cnt = 0;
		// 检查输入是否为空

		if (model_.getValueAt(0, 0) == null) {
			JOptionPane.showMessageDialog(null, "属性列名不能为空！");
			return;
		}
		// 属性列名不可以重复
		if (StringUtil.isHere(model_.getValueAt(0, 0).toString(), JDBCUtils.GetTableCol(tbName))) {
			JOptionPane.showMessageDialog(null, "抱歉，该表已存在同名属性列！");
			return;
		}

		if (model_.getValueAt(0, 1) == null) {
			JOptionPane.showMessageDialog(null, "数据类型不能为空！");
			return;
		}
		
		alter = "alter table databaseManager." + tbName + " add " + model_.getValueAt(0, 0).toString() + " "
				+ model_.getValueAt(0, 1).toString();

		if (model_.getValueAt(0, 2) != null && (boolean) model_.getValueAt(0, 2)) {
			alter += " not null ";
		}
		
		if (model_.getValueAt(0, 3) != null && (boolean) model_.getValueAt(0, 3)) {
			if( code.length() != 0 ) {
				JOptionPane.showMessageDialog(null, "已存在加密列!");
				return;
			}
			alter += "comment 'code'";
		}
		
		
		System.out.println(alter);
		// 执行插入列
		int result = -1;
		try {
			result = JDBCUtils.update(alter);
		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(null, "语法错误，请检查您的输入！");
			return;
		}

		// 提示操作成功
		if (result >= 0)
			JOptionPane.showMessageDialog(null, "插入属性列成功！列名为：'" + model_.getValueAt(0, 0).toString() + "'");
		else
			JOptionPane.showMessageDialog(null, "插入失败！请检查您的输入！");

	}

	private void confirmerformed(ActionEvent e) {
		// 获取表字段名和对应类型
		List<String> queryList = JDBCUtils.GetTableColAnd(tbName);
		String[] mid = new String[queryList.size()];
		queryList.toArray(mid);

		String[] qQuery = new String[queryList.size() / 2];
		String[] type = new String[queryList.size() / 2];
		queryList.toArray(mid);
		for (int i = 0; i < queryList.size() / 2; i++) {
			qQuery[i] = mid[2 * i];
			type[i] = mid[2 * i + 1];
		}

		sql = "insert into databaseManager." + tbName + " values(";
		// 检查是否都不为空
		for (int i = 0; i < num; i++) {
			if (model.getValueAt(0, i) == null) {
				JOptionPane.showMessageDialog(null, "请检查插入的数据，其中某项不可以为空。");
				return;
			}
		}
		// 从table中读取编辑的数据
//		System.out.print("aa"+model.getValueAt(0, 0)) ;
		for (int i = 0; i < num; i++) {
			if (i > 0)
				sql += ",";
			
			if( code.equals(qQuery[i]) ) {
//				MainFrm.myt.getDe(model.getValueAt(i, 0).toString());
				System.out.println("find hrer");
				if (type[i].charAt(0) == 'V') {
					//MainFrm.myt.getDe(model.getValueAt(0, i).toString());
					MainFrm.myt.getDe(model.getValueAt(0, i).toString());
					synchronized(MainFrm.myt){
						try {
							MainFrm.myt.wait();
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
					sql += "'" + MainFrm.myt.res + "'";
				}
				else {
					sql += model.getValueAt(0, i) ;
				}
				continue;
			}
			
			if (type[i].charAt(0) == 'V')
				sql += "'" + model.getValueAt(0, i) + "'";
			else
				sql += model.getValueAt(0, i);

		}
		sql += ")";

		System.out.println(sql);

		// 更新数据库中的数据
		int res;
		try {
			res = JDBCUtils.update(sql);
			JOptionPane.showMessageDialog(null, "插入成功！");
		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(null, "插入失败,已存在该主键值或数据类型错误！");
		}

		return;

	}

	private void quitActionperformed(ActionEvent e) {
		int result = JOptionPane.showConfirmDialog(null, "是否确认退出？", "停止添加数据", JOptionPane.YES_NO_OPTION);
		// 退出窗口
		if (result == JOptionPane.YES_OPTION)
			dispose();
		return;
	}

}
